package com.ns.basic.log.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ns.basic.log.bo.LogPageBO;
import com.ns.basic.log.dto.LogPageDto;
import com.ns.basic.log.service.IApiLogService;
import com.ns.basic.log.vo.ApiLogVO;
import com.ns.core.annotations.ReqLog;
import com.ns.core.bo.IdsBO;
import com.ns.core.utils.date.CalendarPattern;
import com.ns.core.utils.date.CalenderUtil;
import com.ns.core.utils.sg.ResultOk;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Calendar;
import java.util.Objects;

/**
 * API请求LOG记录相关操作
 *
 * @author lw
 */
@RestController
@RequestMapping("/api/log/")
@RequiredArgsConstructor
@CrossOrigin
public class ApiLogController {

    private final IApiLogService apiLogService;

    /**
     * 删
     *
     * @param id 参数
     */
    @GetMapping("delete")
    @ReqLog(module = "API日志模块", name = "删")
    public ResultOk delete(String id) {
        return ResultOk.getByBoolean(apiLogService.removeById(id));
    }

    /**
     * 删 - 根据id列表
     */
    @PostMapping("deleteByIds")
    @ReqLog(module = "API日志模块", name = "删")
    public ResultOk deleteByIds(@RequestBody IdsBO bo) {
        return ResultOk.getByLine(apiLogService.delByIds(bo.getIds()));
    }

    /**
     * 删 - 根据日期范围
     *
     * @param startTime 参数
     * @param endTime   参数
     */
    @GetMapping("deleteByStartEnd")
    @ReqLog(module = "API日志模块", name = "删")
    public ResultOk deleteByStartEnd(String startTime, String endTime) {
        int line = apiLogService.deleteByStartEnd(startTime, endTime);
        return ResultOk.getSuccessData(line);
    }

    /**
     * 查 - 集合（参数为null或0时默认忽略此条件）
     */
    @PostMapping("getList")
    @ReqLog(module = "API日志模块", name = "查")
    public ResultOk getList(@RequestBody LogPageBO bo) {
        LogPageDto dto = new LogPageDto();
        BeanUtils.copyProperties(bo, dto);
        if (Objects.nonNull(bo.getEndTime())) {
            String end = CalenderUtil.addStr(CalendarPattern.Y_M_D, bo.getEndTime(), Calendar.DAY_OF_YEAR, 1);
            dto.setEndTime(end);
        }
        Page<ApiLogVO> list = apiLogService.getList(dto);
        return ResultOk.getPageData(list.getTotal(), list.getRecords());
    }

    /**
     * 统计
     */
    @PostMapping("staBy")
    @ReqLog(module = "API日志模块", name = "查")
    public ResultOk staBy(@RequestBody LogPageBO bo) {
        LogPageDto dto = new LogPageDto();
        BeanUtils.copyProperties(bo, dto);
        return ResultOk.getSuccessData(apiLogService.staBy(dto));
    }

}
